import random
from django.core.mail import send_mail
from django.conf import settings
from django_redis import get_redis_connection


def random_str(length=6):
    str = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    random_str = ''.join(random.choices(str, k=length))
    return random_str

def save_code(email, sig ,code):
    ''' 将验证码缓存到 redis '''
    redis_conn = get_redis_connection('verfication')
    pl = redis_conn.pipeline()
    pl.setex('email_%s' % email, settings.EMAIL_CONFIRM_EX, code)
    pl.setex('email_%s_sig' % email, settings.EMAIL_ACTIVE_EX, sig)
    pl.setex('email_%s_flag' % email, settings.EMAIL_AGAIN_EX, 1)
    pl.execute()

def send_email_code(email, sig):
    ''' 发送邮箱验证码 '''
    code = random_str()
    subject = "注册激活"
    html_message = '<div>' \
                        '<p>您好！</p>' \
                        '<p>欢迎注册我的博客</p>' \
                        '<p>您的邮箱为：{0} 。请点击下面的激活按钮来激活您的邮箱</p>' \
                        '<a href="{1}/verification/email/active/{0}/{2}">激活</a>' \
                   '</div>'.format(email, settings.EMAIL_CONFIRM_URL, code)
    try:
        send_mail(subject, '', settings.EMAIL_FROM, [email], html_message=html_message)
        save_code(email, sig, code)
    except:
        pass
